package cn.wolfcode.luowowo.website.resolver;

import cn.wolfcode.louwowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * springMVC参数解析器，解析UserInfo对象
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver{
    @Reference
    private IUserInfoRedisService redisService;

    //标明需要转换的类型，该解析器需要解析的类型
    public boolean supportsParameter(MethodParameter parameter) {
        //贴了UserParam注解以及形式参数是UserInfo类型的时候才返回true
        return parameter.hasParameterAnnotation(UserParam.class)
                && parameter.getParameterType() == UserInfo.class;
    }
    //当supportsParameter返回true的时候才执行，返回值注入到方法的形式参数中
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
        String token = CookieUtil.getToken(request, response);
        UserInfo userInfo = redisService.getUserByToken(token);
        return userInfo;
    }
}
